<?php

namespace app\api\controller;

use app\lib\Qiniu;
use app\lib\traits\Image as imageTrait;
use app\common\BaseHelper;

use app\admin\model\Dynamictype;
use app\admin\model\Communitydynamics;
use app\admin\model\Townconfig;
use app\admin\model\Villages;
use app\admin\model\Member;
use app\admin\model\Image;
use app\admin\service\Dynamic as DynamicService;

use think\Db;
use think\Exception;

/**
 * 动态接口
 */
class Dynamic extends BaseController
{

    use imageTrait;

    /**
     * 首页数据
     */
    public function getDynamicHomeFrame()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $where = [
            'townId' => $param->townId
        ];
        if(isset($param->villageId) && $param->villageId){
            $where['villageId'] = ['in', ['0', $param->villageId]];
        }

        // 信息分类
        $typeWhere = $where;
        $dynamictypes = $this->getDynamictypes($typeWhere, 7);

        // 信息列表
        $dyWhere = $where;
        $dyWhere['isDelete'] = 2;
        /*if(isset($param->keywords) && $param->keywords){
            $dyWhere['content'] = ['like', '%' . urlencode($param->keywords) . '%'];
        }*/
        $dynamics = $this->getDynamics($dyWhere, $param->type, $param->userId, $start, $length);

        $data = [
            'dynamictypes' => $dynamictypes ? : '',
            'dynamicList' => $dynamics ? : '',
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    // 获取信息（动态）分类列表
    protected function getDynamictypes($where, $limit = 20)
    {
        $model = new Dynamictype();
        $field = 'id, name, imgUrl';
        $result = $model->where($where)->field($field)->limit(0, $limit)->order('sorting ASC')->select();
        if (!$result) {
            return [];
        }

        return $result;
    }

    // 获取信息（动态）列表
    protected function getDynamics($where, $type, $userId, $start, $length)
    {
        $townId = $where['townId'];
        $where['isDelete'] = 2;
        // 动态是否需要审核
        $config = $this->getTownConfig($townId);
        if(isset($config['dongtaicheckoff']) && $config['dongtaicheckoff'] == 1){
            $where['isPass'] = 1;
        }
        $order = 'createDate DESC';

        if ($type == 3) {
            // 我关注的用户
            $userattentionDB = db('userattention');
            $attentionUserIds = $userattentionDB->where(['userId' => $userId])->field('attentionUserId')->select();
            $attentionUserIds = array_column($attentionUserIds, 'attentionUserId');
            $where['createUser'] = ['in', $attentionUserIds];
            $model = db('communitydynamics');
            $fields = 'id, content, createUser as userId, createDate, countComment, countLike';
            $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
            $total = $model->where($where)->count();

            /*$model = db('userattention');
            $join = [
                ['__USER__ u', 'a.attentionUserId = u.id'],
            ];
            $fields = 'a.attentionUserId ,u.id as userId, u.nickName, u.avatarUrl';
            $result = $model->alias('a')->where($where)->join($join)->limit($start, $length)->field($fields)->select();
            $total = $model->alias('a')->where($where)->join($join)->count();*/
        } else {
            if($type == 2){
                $order = 'countLike DESC';
            }

            $model = db('communitydynamics');
            $fields = 'id, content, createUser as userId, createDate, countComment, countLike';
            $result = $model->where($where)->field($fields)->limit($start, $length)->order($order)->select();
            $total = $model->where($where)->count();
        }

        if (!$result) {
            return [];
        }

        $userattentionDB = db('userattention');
        foreach ($result as &$item) {
            $item = DynamicService::formatDynamic($item, $userId);

            if(isset($param->type) && $type == 3){
                $item['isAttention'] = 1;
            }else{
                // 是否已关注
                $isAttention = $userattentionDB->where(['userId' => $userId, 'attentionUserId' => $item['userId']])->find();
                if($isAttention){
                    $isAttention = 1;
                }else{
                    $isAttention = 2;
                }
                $item['isAttention'] = $isAttention;
            }
        }

        return [
            'data' => $result,
            'total' => $total
        ];
    }

    /**
     * 信息（动态）分类列表
     */
    public function getDynamicTypeList()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }

        $where = [
            'townId' => $param->townId
        ];
        $list = $this->getDynamictypes($where, 100);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $list);
    }

    /**
     * 信息（动态）列表
     */
    public function getDynamicList()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->type)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 不能为空');
        }
        if (!in_array($param->type, [1, 2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'type 格式不正确');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $userId = $param->userId;
        $where = [
            'townId' => $param->townId,
            'isDelete' => 2
        ];
        if(isset($param->typeId) && $param->typeId){
            $where['typeId'] = $param->typeId;
        }
        if(isset($param->keywords) && $param->keywords){
            $where['content'] = ['like', '%' . urlencode($param->keywords) . '%'];
        }

        $list = $this->getDynamics($where, $param->type, $userId, $start, $length);
        if (!$list) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关信息');
        }

        $dynamictype = '';
        if(!empty($param->typeId)) {
            $dynamictype = Dynamictype::where(['id' => $param->typeId])->find();
        }

        $data = [
            'dynamictype' => $dynamictype,
            'list' => $list['data']
        ];
        $total = $list['total'];

        return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data, $total);
    }

    /**
     * 发布动态
     */
    public function postDynamic()
    {
        $param = self::getHttpParam();

        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (empty($param->typeId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'typeId 不能为空');
        }
        $Townconfig = Townconfig::where('townId',$param->townId)->find();
        if(!$Townconfig || $Townconfig->dongtaioff == 0){
            // 非村民不能发布动态
            $User = \app\admin\model\User::get($param->userId);
            if(!$User->memberId){
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '您不是村民，没有权限发动态');
            }
            $memberInfo = Member::where(['id' => $User->memberId])->field('checkVillager')->find();
            if($memberInfo['checkVillager'] != 1){
                return show(config('status.ERROR_STATUS'), self::MSG_ERROR, '村居民审核还未通过，不能发动态');
            }
        }
        if (empty($param->content) || !trim($param->content)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '动态内容不能为空');
        }
        /*if (empty($param->imgIds) || !trim($param->imgIds)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'imgIds 不能为空');
        }*/

        $villageId = 0;
        if(isset($param->villageId) && $param->villageId){
            $villageId = $param->villageId;
        }

        $userId = $param->userId;
        $areaIds = $this->getParentIdsByTownId($param->townId);

        Db::startTrans();
        try {
            $model = db('communitydynamics');
            $data = [
                'id' => BaseHelper::getUUID(),
                'createDate' => time(),
                'cityId' => $areaIds['cityId'],
                'xianId' => $areaIds['xianId'],
                'townId' => $param->townId,
                'typeId' => $param->typeId,
                'villageId' => $villageId,
                'createUser' => $userId,
                'content' => $param->content,
            ];

            $result = $model->insert($data);

            if($result !== false){
                // 图片
                //$res = $this->_upload_images($data['id'], $msg);
                $res = '';
                if(isset($param->imgIds) && $param->imgIds) {
                    $imgIds = (array) $param->imgIds;
                    //$res = Image::where(['id' => ['in', $imgIds]])->update(['relatedId' => $data['id'], 'controller' => 'Communitydynamics', 'relatedTable' => 'Communitydynamics', 'tag' => 'imglist']);
                    foreach($imgIds as $key => $imgId){
                        $res = Image::where(['id' => $imgId])->update(['relatedId' => $data['id'], 'controller' => 'Communitydynamics', 'relatedTable' => 'Communitydynamics', 'tag' => 'imglist', 'sorting' => $key]);
                    }
                }
                if($res === false){
                    Db::rollback();
                    return show(config('status.ERROR_STATUS'), self::NOT_DATA, '保存图片失败');
                }
                Db::commit();
            }else{
                Db::rollback();
                return show(config('status.ERROR_STATUS'), self::NOT_DATA, '发布动态失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), '发布动态失败', $e->getMessage());
        }

        // 动态是否需要审核
        $isCheck = 0;
        $config = $this->getTownConfig($param->townId);
        if(isset($config['dongtaicheckoff']) && $config['dongtaicheckoff'] == 1){
            $isCheck = 1;
        }
        $data = [
            'result' => $result,
            'isCheck' => $isCheck
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 动态详情
     */
    public function getDynamicDetail()
    {
        $param = self::getHttpParam();

        if (empty($param->dynamicsId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'dynamicId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }

        $userId = $param->userId;
        $where = [
            'id' => $param->dynamicsId
        ];
        $model = db('communitydynamics');
        $field = 'id, content, createUser as userId, createDate, countRead, countComment, countLike';
        $item = $model->where($where)->field($field)->find();
        if (!$item) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '未查到相关动态');
        }
        $item = DynamicService::formatDynamic($item, $userId);
        // 评论列表
        $item['commentList'] = action('api/common/commentList', ['isApi' => false]);

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $item);
    }

    /**
     * 个人动态
     */
    public function getUserDynamics()
    {
        $param = self::getHttpParam();

        $start = 0;
        $length = 20;
        if (empty($param->townId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'townId 不能为空');
        }
        if (empty($param->postUserId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'postUserId 不能为空');
        }
        if (empty($param->userId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
        }
        if (!empty($param->start)) {
            $start = $param->start;
        }
        if (!empty($param->length)) {
            $length = $param->length;
        }

        $postUserId = $param->postUserId;
        $userId = $param->userId;
        $where = [
            'createUser' => $postUserId,
            'isDelete' => 2
        ];
        $townId = $param->townId;
        // 动态是否需要审核
        $config = $this->getTownConfig($townId);
        if(isset($config['dongtaicheckoff']) && $config['dongtaicheckoff'] == 1){
            $where['isPass'] = 1;
        }

        $userDB = db('user');
        $userattentionDB = db('userattention');
        $userInfo =  $userDB->where(['id' => $postUserId])->field('id,memberId,nickName,avatarUrl')->find();
        // 关注人数
        $countAttention = $userattentionDB->where(['attentionUserId' => $postUserId])->count();
        $userInfo['countAttention'] = $countAttention;
        // 是否已关注
        $isAttention = $userattentionDB->where(['userId' => $userId, 'attentionUserId' => $postUserId])->find();
        if($isAttention){
            $isAttention = 1;
        }else{
            $isAttention = 2;
        }
        $userInfo['isAttention'] = $isAttention;

        $model = db('communitydynamics');
        $fields = 'id, content, createUser as userId, createDate, countComment, countLike';
        $result = $model->where($where)->field($fields)->limit($start, $length)->order('createDate DESC')->select();
        $total = $model->where($where)->count();

        if (!$result) {
            return show(config('status.ERROR_STATUS'), self::NOT_DATA, '没有相关信息');
        }
        $result = DynamicService::formatDynamicList($result, $userId, $userInfo);

        if($userInfo['memberId'] && $userInfo['memberId'] !== 0){
            $memberInfo = Member::where(['id' => $userInfo['memberId']])->field('name,avatar,villageId,job')->find();

            $userInfo['nickName'] = $memberInfo['name'];
            $userInfo['avatarUrl'] = $memberInfo['avatar'];
        }

        $data = [
            'userInfo' => $userInfo,
            'dynamics' => $result,
            'total' => $total
        ];

        //return showTotal(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $result, $total);
        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 删除动态
     */
    public function delDynamic()
    {
        $param = self::getHttpParam();

        if (empty($param->dynamicsId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'dynamicId 不能为空');
        }
//        if (empty($param->userId)) {
//            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, 'userId 不能为空');
//        }

        //$userId = $param->userId;
        $where = [
            'id' => $param->dynamicsId
        ];
        $model = db('communitydynamics');
        $result = $model->where($where)->update(['isDelete' => 1]);
        if ($result === false) {
            return show(config('status.ERROR_STATUS'), '删除失败', '删除失败');
        }

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, []);
    }
}